<template>
  <div class="container">
    <van-nav-bar left-text="返回" left-arrow @click-left="back" />
    <h4 style="margin: 0.5rem 0.3rem">商品分类</h4>
    <van-grid>
      <van-grid-item
        v-for="item in categroy"
        :key="item.id"
        :icon="item.coverImage"
        :text="item.name"
        :to="{ name: 'Pcategroy', params: { id: item.id } }"
      />
    </van-grid>
    <h4 style="margin: 0.5rem 0.3rem">热门商品</h4>
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <van-card
        v-for="i in products"
        :key="i.id"
        :num="i.quantity"
        tag="hot"
        :price="i.price"
        :title="i.name"
        :thumb="i.coverImage"
        origin-price="999.00"
        :thumb-link="'/#/pdetail?id=' + i.id"
      >
        <template #footer>
          <van-button
            size="small"
            icon="cart-o"
            type="danger"
            @click="buyit(i.id)"
          ></van-button>
        </template>
      </van-card>
    </van-list>
  </div>
</template>

<script>
import { loadCategories } from "../services/categroies";
import { loadProducts } from "../services/products";
import { addToCart } from "../services/cart";
import { isLogined } from "../utils/tools";
import { Toast } from "vant";
export default {
  data() {
    return {
      categroy: [],
      products: [],
      loading: false,
      finished: false,
      page: 1,
    };
  },
  created() {
    this.loadCateg(), this.loadProduct();
  },
  methods: {
    async loadCateg() {
      const res = await loadCategories();
      console.log(res);
      this.categroy = res.data;
    },
    async loadProduct() {
      const res = await loadProducts(this.page);
      this.products = [...this.products, ...res.data];
      this.page++;
      this.loading = false;
      if (this.page > res.pages) {
        this.finished = true;
      }
    },
    async buyit(id) {
      if (isLogined()) {
        await addToCart(id, 1);
        Toast.success("加入购物车成功");
        this.$router.push({
          name: "Cart",
        });
      }
    },
    onLoad() {
      console.log("到底了");
      this.loading = true;
      this.loadProduct();
    },
    back() {
      window.history.go(-1);
    },
  },
};
</script>

<style scoped>
::v-deep .van-grid .van-icon__image {
  width: 3rem;
  height: 3rem;
}
</style>